package leetcode.editor.offer;

// 剑指 Offer 67. 把字符串转换成整数
// https://leetcode.cn/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/
class BaZiFuChuanZhuanHuanChengZhengShuLcof {
    public static void main(String[] args) {
        Solution solution = new BaZiFuChuanZhuanHuanChengZhengShuLcof().new Solution();
        solution.strToInt("   -42");
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        /*public int strToInt(String str) {
            int i = 0;
            int length = str.length();
            int sign = 1; // 用来标志符号位
            int res = 0;    // 数字结果
            int bndry = Integer.MAX_VALUE / 10; // 数字边界
            while (str.charAt(i) == ' ') {  // 去掉空格
                // 判断是否超过长度
                if (++i == length) return 0;
            }
            // 判断符号位
            if (str.charAt(i) == '-') sign = -1;    // 此时是负号
            if (str.charAt(i) == '+' || str.charAt(i) == '-') i++;  // 移动到数字位
            for (int j = i; j < length; j++) {
                char x = str.charAt(j);
                if (x > '9' || x < '0') break;  // 不是数字，跳出循环
                // 判断数组是否越界
                if (res > bndry || (x > '7' && res == bndry))
                    return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                res = 10 * res + (x - '0'); // 计算数字
            }

            return sign * res;
        }*/

        public int strToInt(String str) {
            if (str == null || str.length() == 0) return 0;
            char[] arr = str.trim().toCharArray();
            if (arr.length == 0) return 0;
            boolean isNegative = arr[0] != '-';
            int ret = 0, bndry = Integer.MAX_VALUE / 10;
            for (int i = 0; i < arr.length; i++) {
                char c = arr[i];
                if (i == 0 && (c == '-' || c == '+')) continue;
                if (c < '0' || c > '9') break;
                if (ret > bndry || ret == bndry && arr[i] > '7')
                    return isNegative ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                ret = ret * 10 + (c - '0');
            }

            return isNegative ? ret : -ret;
        }

    }
//leetcode submit region end(Prohibit modification and deletion)

}
